import { Component, createContext, forwardRef } from "react";

const UserContext = createContext();
UserContext.displayName = "UserContext";

//提供全局的数据
export class UserProvider extends Component {
  state = {
    isLogin: !!localStorage.getItem("token"),
  };

  loginAction = (value) => {
    this.setState({ isLogin: value });
    return;
  };

  render() {
    const { isLogin } = this.state;
    const value = {
      isLogin,
      loginActions: this.loginAction,
    };
    return (
      <UserContext.Provider value={value}>
        {this.props.children}
      </UserContext.Provider>
    );
  }
}

//高阶组件：使用了高阶组件，就可以通过props获取provider的数据
export function withUserStore(Com) {
  return forwardRef(function NewCom(props, ref) {
    const newProps = {
      ...props,
      ref: ref,
    };
    return (
      <UserContext.Consumer>
        {(value) => <Com {...newProps} userStore={value} />}
      </UserContext.Consumer>
    );
  });
}
